/**
 * Class: OpenLayers.Layer.WeBaidu
 * A class to exploring Baidu Map
 * 
 * Inherits from:
 *  - <OpenLayers.Layer.XYZ>
 */
OpenLayers.Layer.WeBaidu = OpenLayers.Class(OpenLayers.Layer.XYZ, {
    attribution: "&copy; 2011 Baidu - GS(2011)6006号 - Data &copy; <a href='http://www.navinfo.com.cn/'>NavInfo</a> &amp; <a href='http://www.cennavi.com.cn'>CenNavi</a>",
    sphericalMercator: true,
    wrapDateLine: true,
    
    url: [
        //'http://q3.baidu.com/it/u=x=195;y=63;z=10;v=006;type=web&fm=44'
        'http://q1.baidu.com/it/u=x=${x};y=${y};z=${z};v=006;type=web&fm=44',
        'http://q2.baidu.com/it/u=x=${x};y=${y};z=${z};v=006;type=web&fm=44',
        'http://q3.baidu.com/it/u=x=${x};y=${y};z=${z};v=006;type=web&fm=44',
        'http://q4.baidu.com/it/u=x=${x};y=${y};z=${z};v=006;type=web&fm=44',
        'http://q5.baidu.com/it/u=x=${x};y=${y};z=${z};v=006;type=web&fm=44',
        'http://q6.baidu.com/it/u=x=${x};y=${y};z=${z};v=006;type=web&fm=44',
        'http://q7.baidu.com/it/u=x=${x};y=${y};z=${z};v=006;type=web&fm=44',
        'http://q8.baidu.com/it/u=x=${x};y=${y};z=${z};v=006;type=web&fm=44'
    ],
    
    initialize: function(name, url, options) {
        OpenLayers.Layer.XYZ.prototype.initialize.apply(this, arguments);
        this.name = name ? name : OpenLayers.i18n('WeBaidu_name');
    },
    
    getURL: function(bounds) {
        var res = this.map.getResolution();
        var x = Math.round((bounds.left - this.maxExtent.left) 
            / (res * this.tileSize.w));
        var y = Math.round((this.maxExtent.top - bounds.top) 
            / (res * this.tileSize.h));
        var z = 17 - (this.map.getZoom() + this.zoomOffset);
        
        var limit = Math.pow(2, z);
        if (this.wrapDateLine) {
           x = ((x % limit) + limit) % limit;
        }

        var url = this.url;
        var s = '' + x + y + z;
        if (url instanceof Array)
        {
            url = this.selectUrl(s, url);
        }
        
        var path = OpenLayers.String.format(url, {'x': x, 'y': y, 'z': z});

        return path;
    },
    
    clone: function(obj) {
        if (obj == null) {
            obj = new OpenLayers.Layer.WeBaidu(
                this.name, this.url, this.getOptions());
        }
        obj = OpenLayers.Layer.XYZ.prototype.clone.apply(this, [obj]);
        return obj;
    },
    
    CLASS_NAME: "OpenLayers.Layer.WeBaidu"
});
